<?
class DumpUtility {
	
	
	public function _mysqldump($mysql_database,$table='',$where='',$localdb)
	{
		$db = DBCon::instance();
			
		$sql=" use ". $mysql_database;
		$db->executeCommand($sql);
		
		$sql="show tables";
		$result = $db->executeQuery($sql);
		$sqltext = array();
		if( $result)
		{
			foreach($result as $key => $value)
			{
				//DumpUtility::mysqldump_table_structure($value['Tables_in_'.$mysql_database]);
				$thistable = $value['Tables_in_'.$mysql_database];
				if(strlen($table) > 0) {
					if(stripos($table,$thistable) > 0) {
						$sqltext[] = DumpUtility::mysqldump_table_data($mysql_database,$thistable,$where,$localdb);
					}
				}
				else{
					$sqltext[] = DumpUtility::mysqldump_table_data($mysql_database,$thistable,$where,$localdb);
				}
				
			}
		}
		else
		{
			echo "/* no tables in $mysql_database */\n";
		}
		return $sqltext;
			
	}
	
	public function mysqldump_table_structure($table)
	{
		echo "/* Table structure for table `$table` */\n";
		if( isset($_REQUEST['sql_drop_table']))
		{
			echo "DROP TABLE IF EXISTS `$table`;\n\n";
		}	
		if( isset($_REQUEST['sql_create_table']))
		{
		
			$sql="show create table `$table`; ";
			$result=mysql_query($sql);
			if( $result)
			{
				if($row= mysql_fetch_assoc($result))
				{
					echo $row['Create Table'].";\n\n";
				}
			}
			mysql_free_result($result);
		}
	}
	
	public function mysqldump_table_data($dbs,$table,$where='',$localdb)
	{
		$text = '';
		$db = DBCon::instance();
			
		$sql="select * from $dbs.$table;";
		
		$result=$db->executeQuery($sql);
		//print_r($result);die();
		if( $result)
		{
			$num_rows= count($result);
			$num_fields= count($result[0]);
			
			if( $num_rows > 0)
			{
				$text = "use $localdb;";
				$text .= "/* dumping data for table `$table` */\n";
			
				$field_type=array();
				
				
				$index=0;
				
				foreach($result as $key => $value)	
				{
					$i=0;
					if(isset($value["org_id"])) {
						if($where != $value["org_id"])
							continue;
					} 
					$text .= "REPLACE into $table values\n";
					$text .= "(";
					foreach($value as $field => $data){
							$i++;
							$text .= "'".$data."'";
						
							if( $i < $num_fields)
								$text .= ",";
					}
					$text .= ");";
				
					//if( $index < $num_rows-1)
					//	$text .= ",";
						
					$text .= "\n";
					$index++;
				}
					$text .= ";";
					
			}
		}		
		$text .= "\n";
		return $text;
	}	

}
?>